package com.jason.quectel0805.activities;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.jason.quectel0805.R;
import com.jason.quectel0805.database.DbPerson;
import com.jason.quectel0805.database.MySQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;

public class SqliteActivity extends AppCompatActivity {
    private static final String TAG = "jasonwan";
    SQLiteDatabase writableDatabase;
    SQLiteDatabase readableDatabase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sqlite);

        MySQLiteOpenHelper openHelper = new MySQLiteOpenHelper(this, "quectel", null, 1);
        writableDatabase = openHelper.getWritableDatabase();
        readableDatabase = openHelper.getReadableDatabase();

    }

    public void saveData(View view) {
        writableDatabase.execSQL("insert into person (name,age,sex) values ('jason',18,'男')");
    }

    public void readData(View view) {
        Cursor cursor = readableDatabase.rawQuery("select * from article", null);
        int count = cursor.getCount();
        List<DbPerson> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            long id = cursor.getLong(0);
            String name = cursor.getString(1);
            int age = cursor.getInt(2);
            String sex = cursor.getString(3);
            DbPerson person = new DbPerson(id, name, age, sex);
            list.add(person);
        }
        StringBuilder sb = new StringBuilder();
        for (DbPerson dbPerson : list) {
            sb.append(dbPerson.toString());
            Log.d(TAG, "readData: " + dbPerson.toString());
        }
        Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
    }
}